/*
 * AppServer.cpp
 *
 *  Created on: 22 sept. 2009
 *      Author: CHETIER
 */

#include <iostream>
#include <SFML/Network.hpp>

#include "PacketTransmitter.h"
#include "ClientManager.h"
#include "Config.h"

int main()
{
	sf::SocketUDP Listener;
	if (!Listener.Bind(PORT_CLIENT_TO_SERVER))
	{
		std::cout << "Error while binding listener socket!" << std::endl;
		return EXIT_FAILURE;
	}

	std::cout << "Server ready..." << std::endl;
	ClientManager clientManager;

	sf::Clock clock;
	clock.Reset();

	while (true)
	{
		PacketInfo packetToReceive;
		sf::IPAddress sender;
		unsigned short port;
		ClientInfo clientInfo;

		if (Listener.Receive(packetToReceive, sender, port) != sf::Socket::Done)
		{
			std::cout << "error while receiving packet" << std::endl;
			return EXIT_FAILURE;
		}

		//Think
		float ElapsedTime = clock.GetElapsedTime();
		clock.Reset();
		for(ClientManager::iterator i = clientManager.begin(); i != clientManager.end(); ++i)
		{
			if(i->left) i->x -= 50*ElapsedTime;
			if(i->right) i->x += 50*ElapsedTime;
			if(i->up) i->y -= 50*ElapsedTime;
			if(i->down) i->y += 50*ElapsedTime;
		}

		//Transform packet into ClientInfo
		packetToReceive >> clientInfo;

		//Check if the Client is known
		if(!clientManager.Contains(clientInfo))
		{
			clientInfo.ipAdress = sender;
			clientManager.push_back(clientInfo);
			std::cout<< "Welcome " << clientInfo.name << " (" << sender.ToString() << ")" << std::endl;
		}

		//Get the instance of the stored ClientInfo
		ClientInfo& clientInfoBuffer = clientManager[clientManager.IndexOf(clientInfo)];
		clientInfoBuffer.down = clientInfo.down;
		clientInfoBuffer.up = clientInfo.up;
		clientInfoBuffer.left = clientInfo.left;
		clientInfoBuffer.right = clientInfo.right;

		//Send packet to client
		for(ClientManager::iterator i = clientManager.begin(); i != clientManager.end(); ++i)
		{
			//TODO create a PacketTransmitter repository
			PacketTransmitter packetTransmitter;
			packetTransmitter.SendToClient(i->ipAdress, clientManager);
			//packetTransmitter.SendToClient(sf::IPAddress("127.0.0.1"), clientManager);
		}

		//Trace ClientInfo properties
		std::cout << clientInfo.name << " (" << clientInfo.x << ";" << clientInfo.y << "). "
		 << (clientInfo.left ? " Left " : "-")
		 <<	(clientInfo.right ? " Right " : "-")
		 << (clientInfo.up ? " Up ": "-")
		 << (clientInfo.down ? " Down " : "-")
		 << std::endl;
	}

	return EXIT_FAILURE;
}
